/*
 *  Class name: UserDAOImpl.java
 *  Version: 1.0
 *  Date: 20.6.2014
 */
package cz.morosystems.personwebmanager.persistencelayer.daos.impl;

import cz.morosystems.personwebmanager.persistencelayer.daos.UserDAO;
import cz.morosystems.personwebmanager.persistencelayer.entities.User;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

/**
 *
 * @author Michal Ďuriš
 */
@Repository
public class UserDAOImpl implements UserDAO {

    @Autowired
    private SessionFactory sessionFactory;

    public UserDAOImpl() {
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    @Override
    public void addUser(User user) {

        sessionFactory.getCurrentSession().persist(user);
    }

    @Override
    public void changeUser(User user) {

        sessionFactory.getCurrentSession().merge(user);
    }

    @Override
    public void deleteUser(Long userID) {

        sessionFactory.getCurrentSession().delete(getUserByID(userID));
    }

    @Override
    public List<User> getAllUsers() {

//        return sessionFactory.getCurrentSession().createCriteria(User.class)
//                .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
        
        return sessionFactory.getCurrentSession().createQuery(
                "SELECT DISTINCT user "
                + "FROM User as user LEFT JOIN FETCH user.books "
            + "ORDER BY user.name").list();
    }

    @Override
    public User getUserByID(Long userID) {

        if (userID == null || userID <= 0) {
            throw new IllegalArgumentException();
        }

//        return (User) sessionFactory.getCurrentSession().get(User.class, userID);
        
        return (User) sessionFactory.getCurrentSession().createQuery(
                "FROM User as u LEFT JOIN FETCH u.books WHERE u.id = :userID")
                .setParameter("userID", userID).uniqueResult();
    }

}
